<template>
    <div class="main">
        <div class="herder">
            <div style="color: #333333;">
                <h1>SMSoDFP Warning Results</h1>
            </div>
            <div style="margin-bottom: 10px;padding-top: 15px;">
                <button @click="selectModel" style="border: 1px solid #aaa; padding: 1px; margin-right: 18px;">
                    Upload model
                </button>

                <input style="display: none;" id="xlsx" type="file" name="file" />
                <label style="border: 1px solid #aaa; padding: 1px; margin-right: 8px;cursor: pointer;" for="xlsx">
                    Import Data
                </label>
                <!-- <el-button size="mini" @click="dialogVisible = true">创建标注</el-button> -->

                <el-dialog
                    title="提示"
                    :visible.sync="dialogVisible"
                    width="30%"
                    :before-close="handleClose">
                    名称： <el-input v-model="input" placeholder="请输入内容"></el-input>
                    正常值： <el-input v-model="input1" placeholder="请输入内容"></el-input>
                    预警值：<el-input v-model="input2" placeholder="请输入内容"></el-input>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="createMarker">确 定</el-button>
                    </span>
                </el-dialog>
                <label style=" margin-right: 8px;" for="normalColor">
                    Normal value：<input
                        id="normalColor"
                        @change="normalColorChange"
                        v-model="normalColorValue"
                        type="color"
                    />
                </label>
                <label style=" margin-right: 8px;" for="alarmColor">
                    Alarm value：<input id="alarmColor" @change="alarmColorChange" v-model="alarmColorValue" type="color" />
                </label>
                <!-- <label style=" margin-right: 8px;" for="anchor">
                <input id="anchor" type="checkbox" value="0" checked />显示锚点
                </label>
                <label style=" margin-right: 8px;" for="marking">
                <input id="marking" type="checkbox" value="0" checked />显示标注
                </label> -->
                <!-- <div id="demo"></div> -->
            </div>
        </div>
        <div class="view-model-wrap">
            <ViewModel @on-loaded-model="onLoadedModel" :modelUrn="modelUrn"></ViewModel>
        </div>
        <!--echarts 容器-->
        <div id="main" style="width: 80%;height:400px;margin-left: 10%;"></div>
    </div>
</template>

<script>
// @ is an alias to /src
import ViewModel from '@/components/view-model.vue';
import { Files, BimModel } from '@aecworks/bimbox-toolkit';
import { FileReaderXlsx } from '../utils/file-reader-xlsx';
import { recreateMarkers, initMarkerddin, createMarkerByModel } from '../utils/marker-addin';
import { colorRgb } from '../utils/transferRGB';
import { getEchsrtsData } from '../utils/echarts-config';
import { RuntimeUtils } from '../utils/runtime-util';
const MapXlsxData = {};
export default {
    name: 'main-page',
    components: {
        ViewModel,
    },
    data() {
        return {
            input: '',
            input1: '',
            input2: '',
            modelUrn: '',
            obvApi: '',
            normalValue: [],
            MapAlarmData: [],
            alarmValue: [],
            normalColorValue: '#00ff00',
            alarmColorValue: '#ff0000',
            dialogVisible: false,
            activeSelectedNodeIdArray: [],
        };
    },
    methods: {
        createMarker(){
            createMarkerByModel(this.obvApi, {name: this.input,nodeIdArray: this.activeSelectedNodeIdArray})
           this.dialogVisible = false 
        },
        normalColorChange() {
            this.selectAlarmValue(
                this.normalValue,
                this.alarmValue,
                colorRgb(this.normalColorValue).split(','),
                colorRgb(this.alarmColorValue).split(','),
            );
        },
        alarmColorChange() {
            this.selectAlarmValue(
                this.normalValue,
                this.alarmValue,
                colorRgb(this.normalColorValue).split(','),
                colorRgb(this.alarmColorValue).split(','),
            );
        },
        onLoadedModel(obvApi) {
            this.obvApi = obvApi;
            obvApi.addEventListener(OBV.ViewerEventTypes.SelectionChangedEvent, (result) => {
                this.activeSelectedNodeIdArray = result.nodeIdArray
            })   
            initMarkerddin(obvApi);
        },
        selectModel() {
            const bim = new Files(window, window.top, RuntimeUtils.instance.bimboxOrigin);
            const data = {
                modelName: '',
                files: [],
            };
            bim.fileSelectionDialog(data)
                .then(async (result) => {
                    this.modelUrn = await this.getLatestModelUrn(result.files);
                })
                .catch((err) => {
                    console.log(err);
                    // debugger;
                });
        },
        async getLatestModelUrn(files) {
            const data = {
                modelId: files,
            };
            const bimModel = new BimModel(window, window.top, RuntimeUtils.instance.bimboxOrigin);
            const result = await bimModel.gitBimLatestFiles(data);
            return result.urnList.join(',');
        },
        onSelectXlsxChange(fileData) {
            //导入
            if (!fileData.files) {
                return;
            }
            const file = fileData.files[0];
            FileReaderXlsx.reader(file, (data, echartData) => {
                this.getModelDataById(data);
                this.mapEchartsData(echartData);
            });
        },
        async getModelDataById(data) {
            let arr = [];
            const promiseList = data.map((item) => this.getSearchValue(item));
            for (const promise of promiseList) {
                const properties = await promise;
                if (properties) {
                    arr.push(properties);
                }
            }
            this.getAlarmValue(arr);
        },

        mapEchartsData(data) {
            const dataX = [];
            const dataY = [];
            data.forEach((item) => {
                dataX.push(item['监测时间']);
                dataY.push(item['监测值']);
            });
            getEchsrtsData(dataX, dataY);
        },
        getAlarmValue(propertiesArr) {
            propertiesArr.forEach((val) => {
                let properties = val.properties;
                let dbId = val.dbId;
                if (properties.length > 0) {
                    for (let i = 0; i < properties.length; i++) {
                        if (properties[i].displayName === '报警值') {
                            if (properties[i].displayValue >= MapXlsxData[dbId]['监测值']) {
                                this.normalValue.push(val);
                            } else {
                                let temp = {};
                                temp = MapXlsxData[dbId];
                                temp['报警值'] = properties[i].displayValue;
                                temp.dbId = dbId;
                                temp.modelId = val.modelId;
                                this.MapAlarmData.push(temp);
                                this.alarmValue.push(val);
                            }
                            break;
                        }
                    }
                }
            });
            this.selectAlarmValue(
                this.normalValue,
                this.alarmValue,
                colorRgb(this.normalColorValue).split(','),
                colorRgb(this.alarmColorValue).split(','),
            );
        },
        selectAlarmValue(normalValue, alarmValue, normalColorValue, alarmColorValue) {
            normalValue.forEach((item) => {
                this.obvApi.setObjectsColor(
                    { dbId: item.dbId, modelId: item.modelId },
                    normalColorValue[0],
                    normalColorValue[1],
                    normalColorValue[2],
                );
            });
            alarmValue.forEach((item) => {
                this.obvApi.setObjectsColor(
                    { dbId: item.dbId, modelId: item.modelId },
                    alarmColorValue[0],
                    alarmColorValue[1],
                    alarmColorValue[2],
                );
            });
            recreateMarkers(this.obvApi, this.MapAlarmData);
        },
        getSearchValue(item) {
            const modelId = this.obvApi.getModelIds()[0];
            return new Promise((resolve, reject) => {
                this.obvApi.search(
                    undefined,
                    item.ID + '',
                    (arrData) => {
                        MapXlsxData[arrData[0]] = item;
                        this.obvApi.getProperties(
                            { dbId: arrData[0], modelId },
                            (properties) => {
                                properties.modelId = modelId;
                                resolve(properties);
                            },
                            (err, str) => {
                                console.log(str);
                                reject(err);
                            },
                        );
                    },
                    () => {},
                    'ID',
                );
            });
        },
        initXlsx() {
            const xlsxDoc = document.getElementById('xlsx');
            xlsxDoc.addEventListener('change', () => {
                this.onSelectXlsxChange(xlsxDoc);
                xlsxDoc.files = null;
            });
        },
    },
    mounted() {
        this.initXlsx();
    },
};
</script>

<style scoped>
.main {
    width: 100%;
    height: 100%;
    text-align: center;
    overflow: auto;
}

.view-model-wrap {
    width: 80%;
    height: 700px;
    position: relative;
    display: inline-block;
}
</style>
